<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

class Dispatcher
{
    protected $_controllers = array();

    public function dispatch($request, $response) {
        $module = $request->get_module();
        $className = $request->get_controller();

        if(!isset($this->_controllers[$module][$className])) {
            $file = LIB_ROOT . 'modules/' . $request->get_module(). '/' . $className . '.php';
            if(!file_exists($file)) {
                exit('the controller ' . $className . ' not exist!');
            }

            Loader::loadClass('Controller');
            require($file);
            $this->_controllers[$module][$className] = new $className();
            $this->_controllers[$module][$className]->init($request, $response);
        }
        
        ob_start();
        $this->_controllers[$module][$className]->dispatch();
        $body = ob_get_clean();
        $response->setBody($body);
    }
}